<template>
  <div id="register">
    <!-- 导航栏 -->
    <van-nav-bar
      left-text="返回"
      left-arrow
      @click-left="onClickReturn"
      fixed
      z-index="3"
    />
    <!-- 头部信息 -->
    <span class="msg">注册</span>
    <!-- 侧边栏图片 -->
    <van-image
      :src="asideSrc[1]"
      class="asiedImg"
      width="120px"
      height="120px"
      radius="60px 0 0px 60px"
      style="z-index: 1"
    ></van-image>
    <van-image
      :src="asideSrc[0]"
      class="asiedImg"
      width="120px"
      height="120px"
      radius="60px 0 0px 60px"
      style="z-index: 2"
    ></van-image>
    <!-- 申请表单 -->
    <van-form @submit="onSubmit" id="registerForm">
      <!-- 基础信息 -->
      <van-tag mark type="primary" size="medium" class="tag">基础信息</van-tag>
      <van-cell-group inset>
        <van-field
          v-model="basic_info.username"
          name="username"
          label="用户名"
          label-width="1.9rem"
          placeholder="请输入用户名"
          left-icon="user-o"
          :rules="[{ validator: usernameValidator, message: '请填写用户名' }]"
        />
        <!-- 密码 -->
        <van-field
          v-model="basic_info.password"
          type="password"
          name="password"
          label="密码"
          label-width="1.9rem"
          placeholder="请输入密码"
          left-icon="question-o"
          :rules="[
            {
              validator: passwordValadator,
              required: true,
              message: '请填写密码',
            },
          ]"
        />
        <!-- 确认密码 -->
        <van-field
          v-model="confirmPwd"
          type="password"
          name="password"
          label="确认密码"
          label-width="1.9rem"
          placeholder="请再次输入密码"
          left-icon="passed"
          :rules="[
            {
              validator: validatorPwd,
              require: true,
              message: '请再次填写密码',
            },
          ]"
        />
        <!-- 上传头像 -->
        <van-field
          v-model="basic_info.avatar"
          name="uploader"
          label="头像上传"
          left-icon="smile-o"
          :rules="[{ require: true, message: '请上传头像' }]"
        >
          <template #input>
            <van-uploader
              v-model="fileList"
              :after-read="readPic"
              :before-read="beforeRead"
              @oversize="onOversize"
              accept="image/*"
              max-count="1"
              :max-size="10 * 1024 * 1024"
              style="margin-left: 120px"
            ></van-uploader>
          </template>
        </van-field>
      </van-cell-group>
      <!-- 详细信息 -->
      <van-tag mark type="primary" size="medium" class="tag">详细信息</van-tag>
      <van-cell-group inset>
        <!-- 真实姓名 -->
        <van-field
          v-model="detail_info.realname"
          name="realname"
          label="真实姓名"
          label-width="1.9rem"
          placeholder="请输入真实姓名"
          left-icon="idcard"
          :rules="[{ required: true, message: '请填写真实姓名' }]"
        />
        <!-- 性别 -->
        <van-field
          name="gender"
          label="性别"
          left-icon="friends-o"
          label-width="1.9rem"
        >
          <template #input>
            <van-radio-group
              v-model="detail_info.gender"
              direction="horizontal"
              icon-size="16px"
              @change="selectGender"
            >
              <van-radio name="1" shape="square"
                >男生<span style="color: blue" class="genderTag"
                  >♂</span
                ></van-radio
              >
              <van-radio name="0" shape="square"
                >女生<span style="color: pink" class="genderTag"
                  >♀</span
                ></van-radio
              >
            </van-radio-group>
          </template>
        </van-field>
        <!-- 学校 -->
        <van-field
          v-model="detail_info.college"
          name="specialty"
          label="学校"
          label-width="1.9rem"
          placeholder="请输入学校"
          :rules="[{ required: true, message: '请填写学校' }]"
          left-icon="hotel-o"
        />
        <!-- 专业 -->
        <van-field
          v-model="detail_info.specialty"
          name="specialty"
          label="专业"
          label-width="1.9rem"
          placeholder="请输入专业"
          :rules="[{ required: true, message: '请填写专业' }]"
          left-icon="desktop-o"
        />
        <!-- 年级 -->
        <van-field
          v-model="detail_info.grade"
          name="grade"
          label="年级"
          label-width="1.9rem"
          placeholder="请输入年级"
          :rules="[{ required: true, message: '请填写年级' }]"
          left-icon="cluster-o"
        />
        <!-- 电话 -->
        <van-field
          v-model="detail_info.phone"
          name="phone"
          label="电话"
          label-width="1.9rem"
          placeholder="请输入电话号码"
          :rules="[
            {
              validator: phoneValidator,
              required: true,
              message: '请填写电话号码',
            },
          ]"
          left-icon="phone-o"
        />
        <!-- 短信验证码 -->
        <van-field
          v-model="verfiedCode"
          name="verfiedCode"
          center
          clearable
          label="短信验证码"
          label-width="1.9rem"
          left-icon="comment-o"
          placeholder="请输入验证码"
          :rules="[
            { required: true, message: '请输入验证码', trigger: 'onBlur' },
          ]"
        >
          <template #button>
            <van-button
              size="small"
              type="primary"
              :disabled="!detail_info.phone || verfied.isSend || !canSend"
              @click="sendVerfyCode"
              >{{ verfied.vbtnMessage }}</van-button
            >
          </template>
        </van-field>
      </van-cell-group>
      <!-- 提交按钮 -->
      <div style="margin: 16px">
        <van-button round block type="primary" native-type="submit">
          申请
        </van-button>
      </div>
    </van-form>
  </div>
</template>
<script>
import {
  Form,
  Field,
  Button,
  Icon,
  CellGroup,
  Toast,
  Tag,
  Image,
  RadioGroup,
  Radio,
  Cell,
  Uploader,
  NavBar,
} from "vant";
import { sendVerfiedCode, reg_tel, VerfyingCode } from "@/utils/verifyCode.js";
import { uploadImage } from "@/utils/uploadImage";
import { register, isRegisted } from "@/api/UserBaseAPI/register.js";
import { cancelPromise } from "@/utils/cancelPromise.js";
export default {
  name: "register",
  data() {
    return {
      //基础信息
      basic_info: {
        username: "",
        password: "",
        avatar: "",
      },
      //详细信息
      detail_info: {
        realname: "",
        gender: "1",
        college: "",
        specialty: "",
        grade: "",
        phone: "",
      },
      //验证码
      verfiedCode: "",
      //确认密码
      confirmPwd: "",
      //发送验证码
      verfied: {
        isSend: false,
        vbtnMessage: "发送验证码",
        vtime: 0,
      },
      //侧边栏图片
      asideSrc: [],
      //文件上传图片
      fileList: [],
      //是否能发送验证码
      canSend: false,
    };
  },
  methods: {
    //发送验证码
    sendVerfyCode() {
      this.verfied.phone = this.detail_info.phone;
      sendVerfiedCode.call(this.verfied);
    },
    //选择性别
    selectGender(name) {
      this.changeAsideImgShow(name);
    },
    // 侧边栏图片变化
    changeAsideImgShow(index) {
      let imgs = document.querySelectorAll(".asiedImg");
      imgs[index].classList.add("appeared");
      imgs[index].classList.remove("disappeared");
      imgs[1 - index].classList.add("disappeared");
      imgs[1 - index].classList.remove("appeared");
    },
    //测试读取图片
    readPic(file) {
      //console.log(file.content); 文件内容
      //console.log(this.fileList);
    },
    //导航栏返回
    onClickReturn() {
      history.back();
    },
    //确认密码校验
    validatorPwd() {
      if (!this.confirmPwd) return "请再次填写密码";
      return this.confirmPwd != this.basic_info.password
        ? "输入的两次密码不一致"
        : true;
    },
    //电话号码校验
    phoneValidator() {
      let phone = this.detail_info.phone;
      if (!reg_tel.test(phone)) {
        this.canSend = false;
        return "请输入正确的手机号";
      }
      //判断当前手机是否已经注册
      return cancelPromise.request(
        "phone",
        isRegisted({ type: "phone", verfieditem: phone })
          .then((res) => {
            if (res.isRegisted) {
              this.canSend = false;
              return "该手机号已注册";
            } else {
              this.canSend = true;
            }
          })
          .catch((err) => {
            Toast.fail({
              duration: 1000,
              orbidClick: true,
              message: err,
            });
            this.canSend = false;
          })
      );
    },
    //密码校验
    passwordValadator() {
      if (this.basic_info.password.indexOf(" ") != -1)
        return "密码不能存在空格";
      let pwd = String(this.basic_info.password);
      if (pwd.length < 6 || pwd.length > 18) {
        return "密码长度需在6到18位之间";
      }
    },
    //用户名校验
    usernameValidator() {
      let username = this.basic_info.username;
      if (!username) return "请填写用户名";
      //判断当前用户名是否已经注册
      return cancelPromise.request(
        "username",
        isRegisted({ type: "username", verfieditem: username })
          .then((res) => {
            if (res.isRegisted) {
              return "该用户名已被注册";
            }
          })
          .catch((err) => {
            Toast.fail({
              duration: 1000,
              orbidClick: true,
              message: err,
            });
          })
      );
    },
    beforeRead(file) {
      //console.log(file.type);
      if (
        file.type === "image/jpeg" ||
        file.type === "image/png" ||
        file.type === "image/jpg"
      ) {
        return true;
      }
      Toast.fail({
        message:"只能上传\njpeg png jpg\n格式文件哦!",
        duration:1500
      })
      return false;
    },
    onOversize(file) {
       Toast.fail({
        message:"头像大小不超过10M",
        duration:1500
      })
    },
    //注册
    onSubmit(values) {
      let params = { ...this.basic_info, ...this.detail_info };
      let fileName = values.uploader[0].file.name;
      let file = values.uploader[0].file;
      const toast1 = Toast.loading({
        duration: 0,
        forbidClick: true,
        message: "注册中...",
        onOpened: async () => {
          let res = await VerfyingCode(values.phone, this.verfiedCode);
          //console.log(res);
          if (res.success) {
            let data = await uploadImage(fileName, file);
            //console.log(data);
            params.avatar = data.url;
            res = await register(params);
            if (res.success) {
              //console.log(res);
              toast1.clear();
              Toast.success({
                duration: 1500,
                forbidClick: true,
                message: "注册成功!",
                onClose: () => {
                  history.back();
                },
              });
            }
          }
        },
      });
    },
  },
  components: {
    [Form.name]: Form,
    [CellGroup.name]: CellGroup,
    [Field.name]: Field,
    [Button.name]: Button,
    [Icon.name]: Icon,
    [Tag.name]: Tag,
    [Image.name]: Image,
    [RadioGroup.name]: RadioGroup,
    [Radio.name]: Radio,
    [Cell.name]: Cell,
    [Uploader.name]: Uploader,
    [NavBar.name]: NavBar,
  },
  computed: {
    //电话号码正则表达式校验
    reg_phone() {
      return reg_tel.test(this.detail_info.phone);
    },
  },
  created() {
    //获取页面右侧静态图片资源列表
    this.asideSrc.push(
      ...[
        require("@/assets/register_pic1.jpeg"),
        require("@/assets/register_pic2.jpeg"),
      ]
    );
  },
};
</script>
<style lang="less" scoped>
@import "../../assets/css/gradient.css";
#register {
  width: 100%;
  height: 100vh;
  overflow: hidden;
  background-color: #f7f8fa;
}
#registerForm {
  position: absolute;
  width: 100%;
  top: 145px;
  left: 50%;
  transform: translate(-50%, 0);
  overflow: hidden;
}
//分类标签
.tag {
  margin: 10px;
  transform: translate(-135px, 0);
}
//头部提示信息
.msg {
  position: absolute;
  top: 65px;
  left: 20px;
  font-size: 26px;
  font-weight: bolder;
  text-align: left;
  letter-spacing: 2px;
}
.msg::after {
  content: "欢迎加入校园社区~";
  display: block;
  font-size: 16px;
  font-weight: normal;
  color: #6d6c6c;
  letter-spacing: 0px;
}
//侧边栏图片
.asiedImg {
  position: absolute;
  top: 50px;
  right: 0px;
  border-radius: 30px;
}
//性别选择标签
.genderTag {
  font-size: 16px;
  font-weight: bolder;
  padding-left: 1px;
}
</style>